package com.fwtai.service;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

/**有返回值,使用阿里巴巴推荐的创建线程池的方式处理业务,线程安全,ok*/
public final class TaskResult<T>{

  //私有的构造方法
  private TaskResult(){}

  //单例对象
  private static final TaskResult<Object> instance = new TaskResult<>();

  //静态的工厂方法
  public static TaskResult<Object> getInstance(){
    return instance;
  }

  private final ThreadPoolExecutor executor = new ThreadPoolExecutor(
    Runtime.getRuntime().availableProcessors()*32,76800,1L,TimeUnit.SECONDS,new LinkedBlockingQueue<>(51200),new ThreadPoolExecutor.CallerRunsPolicy()
  );

  //ok,用法：TaskResult.getInstance().execute(()->{return "";});todo 不能手动关闭释放线程池
  public T execute(final Supplier<T> supplier){
    return CompletableFuture.supplyAsync(supplier,executor).join();
  }

  public String getString(final Supplier<String> supplier){
    return CompletableFuture.supplyAsync(supplier,executor).join();
  }
}